import store from "@/store/store";

class WebSocketClient {
  constructor(config = {}) {
    const defaultConfig = {
      url: "127.0.0.1",
      port: "3001",
      protocol: "ws",
    };
    const finalConfig = { ...defaultConfig, ...config };
    this.ws = {};
    this.url = finalConfig.url;
    this.port = finalConfig.port;
    this.protocol = finalConfig.protocol;
  }
  init() {
    this.ws = new WebSocket(`${this.protocol}://${this.url}:${this.port}`);
    this.ws.onopen = this.onOpen;
    this.ws.onmessage = this.onMessage;
    this.ws.onclose = this.onClose;
    this.ws.onerror = this.onError;
  }
  send(msg) {
    this.ws.send(msg);
  }
  onOpen() {
    //发起鉴权请求
    this.send(
      JSON.stringify({
        event: "auth",
        message: "Bearer " + store.state.token,
      })
    );
  }
  onMessage(event) {
    // console.log(event.data);
    var ob = JSON.parse(event.data);
    switch (ob.event) {
      case "noauth": //鉴权失败
        //跳转到login重新发起请求
        // this.$router.push({ name: "login" });
        break;
      case "heartbeat":
        this.checkServer();
        this.ws.send(
          JSON.stringify({
            event: "heartbeat",
            message: "pong",
          })
        );
        break;
      default:
        store.dispatch(ob.event, ob);
    }
  }
  onClose() {
    console.log("close:" + this.ws.readyState);
    this.ws.close();
  }
  onError() {
    console.log("error:" + this.ws.readyState);
    setTimeout(() => {
      this.init();
    }, 1000);
  }
}

export { WebSocketClient };
